package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"net/rpc"

	"gitee.com/lcc_dr/rpc/rpc_http/service"
)

/*
1、自定义一个函数
2、注册到rpc
3、rpc 启动

*/
var _ service.HelloService = (*HelloServiceClient)(nil)

type HelloServiceClient struct {
	Client *rpc.Client
	/* * rpc.Client 本质是一个Client的结构体

		type Client struct {
		codec ClientCodec

		reqMutex sync.Mutex // protects following
		request  Request

		mutex    sync.Mutex // protects following
		seq      uint64
		pending  map[uint64]*Call
		closing  bool // user has called Close
		shutdown bool // server has told us to stop
	}
	*/
}

func RpcDialHTTP(network, addr string) (*HelloServiceClient, error) {
	client, err := rpc.DialHTTP(network, addr)
	if err != nil {
		panic(err)
	}

	// c := rpc.NewClientWithCodec(jsonrpc.NewClientCodec(client))
	return &HelloServiceClient{Client: client}, nil

}

func (h *HelloServiceClient) Hello(res string, response *string) error {

	err := h.Client.Call(service.SERVICE_NAME+".Hello", res, &response)
	if err != nil {
		panic(err)
	}
	//fmt.Println(&response)

	return nil

}

func (h *HelloServiceClient) Calc(res *service.Calc, response *int) error {

	err := h.Client.Call(service.SERVICE_NAME+".Hello", res, &response)
	if err != nil {
		panic(err)
	}
	//fmt.Println(&response)

	return nil

}

type RpcHttp struct {
	Method string   `json:"method"`
	Params []string `json:"params"`
	Id     int      `json:"id"`
}

// {
// 	"method":"HelloService.Hello",
// 	"params":["world"],
// 	"id":1
// 	}
func main() {

	//1、通过rpc.http 通信
	client, err := RpcDialHTTP("tcp", ":1234")

	if err != nil {

		panic(err)
	}

	var replay string
	err = client.Hello("lcc233", &replay)
	if err != nil {

		panic(err)
	}

	fmt.Printf("rpc.http 进行通信，replay is: %s \n", replay)

	//2、通过标准的http协议进行痛惜
	rpcHttpReq := &RpcHttp{
		Method: "HelloService.Hello",
		Params: []string{"world"},
		Id:     1,
	}
	/*
		访问add
				{
			"method":"HelloService.Calc",
			"params":[{"A":2,"B":4}],
			"id":1
			}

	*/

	reqBody, err := json.Marshal(rpcHttpReq)
	if err != nil {
		panic(err)
	}

	buf := bytes.NewBuffer([]byte(reqBody))
	// httpreq, err := http.NewRequest("POST", "http://127.0.0.1:1234/rpc_http", buf)

	response, err := http.Post("http://127.0.0.1:1234/rpc_http", "application/json", buf)
	// response, err := http.DefaultClient.Do(httpreq)
	fmt.Println(response.StatusCode)
	defer response.Body.Close()
	if err != nil {

		panic(err)
	}
	resbody, err := ioutil.ReadAll(response.Body)

	if err != nil {

		panic(err)
	}

	json.Unmarshal(resbody, &replay)

	fmt.Printf("http 进行通信，replay is: %s \n", string(replay))

}
